using System;
using System.Data;
using System.Data.SQLite;
using BLL;

namespace DAL.Managers
{
    /// <summary>
    /// The manager for the object Author
    /// </summary>
    public class AuthorManager
    {
        #region properties

        private static AuthorManager _sInstance;
        private static readonly object SInstanceLocker = new object();

        #endregion

        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>The instance.</value>
        public static AuthorManager Instance
        {
            get
            {
                lock (SInstanceLocker)
                {
                    return _sInstance ?? (_sInstance = new AuthorManager());
                }
            }
        }

        #region public functions

        /// <summary>
        /// Gets the author by id.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <param name="conn">The connection to the database.</param>
        /// <returns>The author or null.</returns>
        public Author GetAuthorById(Int64 id, SQLiteConnection conn = null)
        {
            Author author;

            if (conn != null)
            {
                // Treatment
                author = GetAuthorByIdTreatment(id, conn);
            }
            else
            {
                using (conn = new SQLiteConnection(Connection.CatalogConnection))
                {
                    conn.Open();

                    // Treatment
                    author = GetAuthorByIdTreatment(id, conn);
                }
            }

            return author;
        }

        #endregion

        #region private functions

        /// <summary>
        /// Gets the author by id (Main treatment).
        /// </summary>
        /// <param name="id">The id.</param>
        /// <param name="conn">The connection to the database (opened).</param>
        /// <returns>The author.</returns>
        private static Author GetAuthorByIdTreatment(Int64 id, SQLiteConnection conn)
        {
            Author author = null;

            // Take the sort_name to pass it to the constructor of Author
            var query = "SELECT sort FROM authors WHERE id=" + id;
            var cmd = new SQLiteCommand(query, conn);

            // Construction of the author
            var reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                // New author
                author = new Author(id, reader[0].ToString());
            }

            // Clear the memory
            reader.Dispose();
            cmd.Dispose();

            return author;
        }

        #endregion


        
    }
}
